// 日期格式化工具
export const formatDate = (date, format = 'YYYY-MM-DD') => {
  const d = new Date(date)
  
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  
  let result = format
  result = result.replace('YYYY', year)
  result = result.replace('MM', month)
  result = result.replace('DD', day)
  result = result.replace('HH', hours)
  result = result.replace('mm', minutes)
  result = result.replace('ss', seconds)
  
  return result
}

// 相对时间格式化
export const formatRelativeTime = (date) => {
  const now = new Date()
  const past = new Date(date)
  const diffMs = now - past
  const diffMins = Math.floor(diffMs / (1000 * 60))
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60))
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  const diffWeeks = Math.floor(diffMs / (1000 * 60 * 60 * 24 * 7))
  const diffMonths = Math.floor(diffMs / (1000 * 60 * 60 * 24 * 30))
  const diffYears = Math.floor(diffMs / (1000 * 60 * 60 * 24 * 365))
  
  if (diffMins < 1) {
    return '刚刚'
  } else if (diffMins < 60) {
    return `${diffMins}分钟前`
  } else if (diffHours < 24) {
    return `${diffHours}小时前`
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else if (diffWeeks < 4) {
    return `${diffWeeks}周前`
  } else if (diffMonths < 12) {
    return `${diffMonths}个月前`
  } else {
    return `${diffYears}年前`
  }
}

// 数字格式化
export const formatNumber = (num, options = {}) => {
  const { decimals = 0, prefix = '', suffix = '', thousandsSeparator = ',' } = options
  
  // 格式化小数
  const formattedNum = Number(num).toFixed(decimals)
  
  // 添加千位分隔符
  let parts = formattedNum.toString().split('.')
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator)
  
  const result = parts.join('.')
  
  // 添加前缀和后缀
  return `${prefix}${result}${suffix}`
}

// 文件大小格式化
export const formatFileSize = (bytes, decimals = 2) => {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB']
  
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

// 文本截断
export const truncateText = (text, maxLength = 100, suffix = '...') => {
  if (!text || text.length <= maxLength) {
    return text
  }
  
  return text.substring(0, maxLength) + suffix
}

// HTML转义
export const escapeHtml = (text) => {
  const div = document.createElement('div')
  div.textContent = text
  return div.innerHTML
}

// HTML解析
export const unescapeHtml = (html) => {
  const div = document.createElement('div')
  div.innerHTML = html
  return div.textContent || div.innerText || ''
}

// 防抖函数
export const debounce = (func, wait = 300) => {
  let timeout
  
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

// 节流函数
export const throttle = (func, limit = 300) => {
  let inThrottle
  
  return function(...args) {
    if (!inThrottle) {
      func.apply(this, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

// 深拷贝
export const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') return obj
  
  if (obj instanceof Date) return new Date(obj.getTime())
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

// 生成唯一ID
export const generateId = (prefix = 'id') => {
  return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
}

// 校验邮箱
export const isValidEmail = (email) => {
  const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return re.test(email)
}

// 校验手机号
export const isValidPhone = (phone) => {
  const re = /^1[3-9]\d{9}$/
  return re.test(phone)
}

// 获取URL参数
export const getUrlParams = (url = window.location.href) => {
  const params = {}
  const parser = document.createElement('a')
  parser.href = url
  const query = parser.search.substring(1)
  const pairs = query.split('&')
  
  for (let i = 0; i < pairs.length; i++) {
    const pair = pairs[i].split('=')
    params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')
  }
  
  return params
}

// 下载文件
export const downloadFile = (url, filename) => {
  const link = document.createElement('a')
  link.href = url
  link.download = filename || 'download'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 复制文本到剪贴板
export const copyToClipboard = async (text) => {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      return true
    } else {
      // 兼容旧版浏览器
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      
      const successful = document.execCommand('copy')
      document.body.removeChild(textArea)
      
      return successful
    }
  } catch (error) {
    console.error('复制失败', error)
    return false
  }
}

// 获取随机颜色
export const getRandomColor = () => {
  const letters = '0123456789ABCDEF'
  let color = '#'
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)]
  }
  return color
}

// 获取主题色
export const getThemeColor = (index = 0, opacity = 1) => {
  const colors = [
    '#3498db', // 蓝色
    '#2ecc71', // 绿色
    '#e74c3c', // 红色
    '#f39c12', // 橙色
    '#9b59b6', // 紫色
    '#1abc9c', // 青色
    '#e67e22', // 深橙色
    '#34495e'  // 深蓝色
  ]
  
  const color = colors[index % colors.length]
  
  if (opacity === 1) {
    return color
  }
  
  // 将hex颜色转换为rgba
  const r = parseInt(color.slice(1, 3), 16)
  const g = parseInt(color.slice(3, 5), 16)
  const b = parseInt(color.slice(5, 7), 16)
  
  return `rgba(${r}, ${g}, ${b}, ${opacity})`
}

// 滚动到指定元素
export const scrollToElement = (element, offset = 0, behavior = 'smooth') => {
  if (typeof element === 'string') {
    element = document.querySelector(element)
  }
  
  if (element) {
    const yOffset = offset
    const y = element.getBoundingClientRect().top + window.pageYOffset + yOffset
    
    window.scrollTo({
      top: y,
      behavior: behavior
    })
  }
}

// 平滑滚动到顶部
export const scrollToTop = (behavior = 'smooth') => {
  window.scrollTo({
    top: 0,
    behavior: behavior
  })
}

// 检查元素是否在视口中
export const isElementInViewport = (element) => {
  if (typeof element === 'string') {
    element = document.querySelector(element)
  }
  
  if (!element) return false
  
  const rect = element.getBoundingClientRect()
  
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  )
}

// 等待指定时间
export const wait = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms))
}

// 打乱数组
export const shuffleArray = (array) => {
  const newArray = [...array]
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[newArray[i], newArray[j]] = [newArray[j], newArray[i]]
  }
  return newArray
}

// 排序数组
export const sortArray = (array, field, order = 'asc') => {
  const newArray = [...array]
  
  newArray.sort((a, b) => {
    let valueA = a[field]
    let valueB = b[field]
    
    // 处理日期类型
    if (valueA instanceof Date && valueB instanceof Date) {
      return order === 'asc' ? valueA - valueB : valueB - valueA
    }
    
    // 转换为字符串进行比较
    valueA = String(valueA).toLowerCase()
    valueB = String(valueB).toLowerCase()
    
    if (order === 'asc') {
      return valueA.localeCompare(valueB)
    } else {
      return valueB.localeCompare(valueA)
    }
  })
  
  return newArray
}

// 分组数组
export const groupArray = (array, field) => {
  return array.reduce((groups, item) => {
    const key = item[field]
    if (!groups[key]) {
      groups[key] = []
    }
    groups[key].push(item)
    return groups
  }, {})
}

// 去重数组
export const uniqueArray = (array, field = null) => {
  if (field) {
    const seen = new Set()
    return array.filter(item => {
      const key = item[field]
      if (seen.has(key)) return false
      seen.add(key)
      return true
    })
  }
  
  return [...new Set(array)]
}